﻿#region Usings

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using ScrumTable.Common;
using ScrumTable.Common.Logging;
using ScrumTable.UI.View.Converter;
using ScrumTable.UI.View.Util;
using ScrumTable.UI.ViewModel.Data;
using Image = System.Drawing.Image;
using ScrumTable.Common.Threading;

#endregion

namespace ScrumTable.UI.View.CustomControl
{
    /// <summary>
    /// Loads a image Async, while loading a loading gif is show
    /// </summary>
    public class WebAsyncReportMemberImage : WebAsyncImage
    {

        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------
        private static readonly Dictionary<Uri, BitmapSource> _changedMemberImages = new Dictionary<Uri, BitmapSource>();
        private static readonly MessageQueue<Uri> _loadMembersQueue = new MessageQueue<Uri>();
        private static readonly BitmapSource _bitmap = new BitmapImage(new Uri(@"pack://application:,,,/ScrumTable.UI.View;component/Resources/person.gif"));
        private static readonly object Lock = new object(); 
        #endregion
     
        #region Methods




        protected override void LoadImageFromUrl(Uri imageUri)
        {

            if (imageUri == null || EmptyUri == imageUri)
            {
                ShowImage(_bitmap);
                return;
            }
           
            lock (Lock)
            {
                if (_changedMemberImages.ContainsKey(imageUri))
                {
                    ShowWebImage(_changedMemberImages[imageUri]);
                    return;
                }
            }
            ShowWaitingImage();
            _loadMembersQueue.Enqueue(new MessageQueueCall<Uri>(DelegateCall), imageUri);

        }

        private void DelegateCall(Uri webUri)
        {
            lock (Lock)
            {
                if (_changedMemberImages.ContainsKey(webUri))
                {
                    ShowWebImage(_changedMemberImages[webUri]);
                    return;
                }
            }

            var image = LoadImageFromUrlSync(webUri);
            BitmapSource imageSource = image == null ? _bitmap : BitmapUtil.CreateBitmapSource(((Bitmap)image));

            lock (Lock)
            {
                _changedMemberImages[webUri] = imageSource;
            }
            ShowWebImage(_changedMemberImages[webUri]);
        }
        #endregion
    }
}
